package cc.rengu.igas.opms.core.service.trans.quickpay;

import cc.rengu.igas.opms.common.constant.OpmsParamConstant;
import cc.rengu.igas.opms.common.enums.RespCodeEnum;
import cc.rengu.igas.opms.core.service.base.ManageService;
import cc.rengu.igas.opms.facade.base.BaseResponse;
import cc.rengu.igas.opms.facade.bean.BindCardInfo;
import cc.rengu.igas.opms.facade.request.SetDefaultPayAcctRequest;
import cc.rengu.igas.opms.facade.response.SetDefaultPayAcctResponse;
import cc.rengu.igas.share.core.realize.UserService;
import cc.rengu.igas.share.core.realize.impl.UserServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SignAcctInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.SignAcctInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.SignAcctInfo;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DbsUtil;
import cc.rengu.oltp.utility.util.XmlConfigUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.List;

/**
 * 设置默认支付卡 服务
 *
 * @author keyi
 * @date 2020/5/12.
 */
public class SetDefaultPayAcctService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        SetDefaultPayAcctRequest setDefaultPayAcctRequest = new SetDefaultPayAcctRequest();
        ConvertUtil.convertOutput(setDefaultPayAcctRequest);
        return setDefaultPayAcctRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        SetDefaultPayAcctRequest setDefaultPayAcctRequest = (SetDefaultPayAcctRequest) request;
        String instId = setDefaultPayAcctRequest.getHeader().getInstId();
        SignAcctInfoMapper signAcctInfoMapper = new SignAcctInfoMapperImpl();

        //step1.获取用户所属主体
        UserService userService = new UserServiceImpl();
        String signInst = userService.getUserSignInst();

        //step2.更新支付扣款顺序
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppParamConstant.DATABASE_CONF_NODE, AppParamConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppParamConstant.OLTP_POOL_NAME);
        }

        /* Step2.1：开启数据库事务 */
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        /* Step2.2：更新签约账号支付顺序 */
        List<BindCardInfo> bindCardList = setDefaultPayAcctRequest.getBindCardList();
        for (BindCardInfo bindCardInfo : bindCardList) {
            //校验签约信息是否存在
            SignAcctInfo signAcctInfo = signAcctInfoMapper.selectSignAcctInfoByPrimaryKey(instId, bindCardInfo.getSignType(), bindCardInfo.getSignToken(), signInst);
            if (null == signAcctInfo || AppParamConstant.NO.equals(signAcctInfo.getSignStatus())) {
                dbsUtil.dbsEndTransaction(false);
                rglog.info("签约信息不存在或已解约");
                throw new BizException(RespCodeEnum.INVALID_SIGN.getRespCode(), RespCodeEnum.INVALID_SIGN.getRespDesc());
            }
            //校验账号是否正确
            if (!signAcctInfo.getSignAcctNo().endsWith(bindCardInfo.getSignAcctNo())) {
                dbsUtil.dbsEndTransaction(false);
                rglog.info("签约账号信息不一致,signAcctNo:<{}>,reqeustAcctNo:<{}>", signAcctInfo.getSignAcctNo(), bindCardInfo.getSignAcctNo());
                throw new BizException(RespCodeEnum.INVALID_SIGN.getRespCode(), RespCodeEnum.INVALID_SIGN.getRespDesc());
            }
            //更新签约数据中的扣款顺序
            signAcctInfo.setPayIndex(Integer.parseInt(bindCardInfo.getPayIndex()));
            if (OpmsParamConstant.INT_ZERO != signAcctInfoMapper.updateSignAcctInfoByPrimaryKey(signAcctInfo, true)) {
                dbsUtil.dbsEndTransaction(false);
                rglog.info("更新签约信息表失败,signAcctInfo:<{}>", JSONObject.toJSONString(signAcctInfo));
                throw new BizException(RespCodeEnum.UPDATE_SIGN_ACCT_ERROR.getRespCode(), RespCodeEnum.UPDATE_SIGN_ACCT_ERROR.getRespDesc());
            }
        }

        /* Step2.3：结束数据库事务 */
        dbsUtil.dbsEndTransaction(true);

        //应答
        BizResponse<BaseResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        SetDefaultPayAcctResponse setDefaultPayAcctResponse = (SetDefaultPayAcctResponse) bizResponse.getResult();
        ConvertUtil.convertInput(setDefaultPayAcctResponse);
    }
}
